package com.maxlen.admin.security;

import com.maxlen.admin.entity.bo.LoginDetailsBo;
import com.maxlen.common.constant.MemberConstant;
import com.maxlen.common.exception.ExceptionCode;
import com.maxlen.common.utils.R;
import com.maxlen.common.utils.RedisUtils;
import com.maxlen.common.utils.ResponseUtils;
import com.maxlen.common.utils.ResultCode;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出登录处理
 */
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {

    private StringRedisTemplate redisTemplate;

    public CustomLogoutSuccessHandler(StringRedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if(!ObjectUtils.isEmpty(authentication)){
            LoginDetailsBo loginDetailsBo = (LoginDetailsBo) authentication.getPrincipal();
            RedisUtils.delete(redisTemplate, MemberConstant.MEMBER_LOGIN + loginDetailsBo.getAdmin().getId().toString());
            ResponseUtils.out(response, R.ok());
        }else{
            ResponseUtils.out(response, R.error(ExceptionCode.USER_NOT_LOGIN));
        }
    }
}
